package com.qiall.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理运行时异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public BusinessResult handleThrowable(Throwable e, HttpServletRequest request) {
        //TODO 运行是异常，可以在这里记录，用于发异常邮件通知
        BusinessResult error = BusinessResult.fail(ResultCode.SYSTEM_ERROR, e);
        log.error("URL:{} ,系统异常: ",request.getRequestURI(), e);
        return error;
    }
    /**
     *处理@notNull绑定异常
     */
    @ExceptionHandler(BindException.class)
    public BusinessResult exceptionHandler(BindException e, HttpServletRequest request) {
        String failMsg = e.getBindingResult().getFieldError().getDefaultMessage();
        BusinessResult error = BusinessResult.fail(ResultCode.SYSTEM_ERROR, e, failMsg);
        log.error("URL:{} ,绑定异常:{} ", request.getRequestURI(),failMsg);
        return error;
    }

    /**
     * 处理自定义异常
     */
    //捕获指定异常
    @ExceptionHandler(BusinessException.class)
    public BusinessResult handleBusinessException(BusinessException e, HttpServletRequest request) {
        BusinessResult error = BusinessResult.builder().status(e.code)
                .message(e.getErrorMessage())
                .exception(e.getClass().getName())
                .build();
        //在控制台会打印出异常的url地址和详细信息
        log.warn("URL:{} ,业务异常:{}", request.getRequestURI(),error);
        return error;
    }

}
